﻿
using System;
using Microsoft.AspNetCore.Mvc.Filters;
using Mrc.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using DotNetEx;

namespace Mrc.Application
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class LoginAttribute : Attribute, IAuthorizationFilter
    {
        public LoginAttribute()
        {

        }
        public virtual void OnAuthorization(AuthorizationFilterContext filterContext)
        {
            if (filterContext.Result != null)
                return;

           // if()

            if (((bool)(filterContext.HttpContext.Items["islogin"] ?? false)) == true)
            {
                return;
            }


            HttpRequest httpRequest = filterContext.HttpContext.Request;
            if (httpRequest.IsAjaxRequest())
            {
                AjaxResult result = AjaxResult.CreateResult(ResultStatus.NotLogin, "未登录或登录超时，请重新登录");
                string json = JsonHelper.Serialize(result);
                ContentResult contentResult = new ContentResult() { Content = json };
                filterContext.Result = contentResult;
                return;
            }
            else
            {
                string url = string.Empty;
                var route = filterContext.RouteData.Values;
                string strArea = (route["area"]??"").ToString();
                if (strArea.ToLower().Equals("admin"))
                {
                  url=filterContext.HttpContext.Content("/Login");
                }
                else
                {
                    url = filterContext.HttpContext.Content("~/Home/index");
                }    
                url = string.Concat(url, "?returnUrl=", httpRequest.Path);
                RedirectResult redirectResult = new RedirectResult(url);
                filterContext.Result = redirectResult;
                return;
            }
        }
    }
}
